<template>
  <!-- 主要内容区域 -->
  <div class="flex-1 p-6 overflow-auto bg-gray-100">
    <div class="bg-white rounded-lg p-6">
      <!-- 搜索区域 -->
      <div class="flex items-center space-x-4 mb-6">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入学生信息"
          class="w-64"
          clearable
        >
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-input
          v-model="searchForm.username"
          placeholder="请输入角色"
          class="w-64"
          clearable
        >
        </el-input>
        <el-input
          v-model="searchForm.phone"
          placeholder="请输入手机号码"
          class="w-64"
          clearable
        >
        </el-input>
        <el-select
          v-model="searchForm.status"
          placeholder="用户状态"
          class="w-32"
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
        <el-button type="primary" class="!rounded-button" @click="handleSearch">
          <el-icon class="mr-1">
            <Search /> </el-icon
          >搜索
        </el-button>
        <el-button class="!rounded-button" @click="handleReset">
          <el-icon class="mr-1">
            <Refresh /> </el-icon
          >重置
        </el-button>
      </div>
      <!-- 操作按钮 -->
      <div class="flex justify-between mb-4">
        <div class="space-x-2">
          <el-button
            type="primary"
            class="!rounded-button"
            @click="openDialog('add')"
          >
            <el-icon class="mr-1">
              <Plus /> </el-icon
            >新增
          </el-button>
          <el-button
            type="danger"
            class="!rounded-button whitespace-nowrap"
            @click="handleDelete"
          >
            <el-icon class="mr-1">
              <Delete /> </el-icon
            >删除
          </el-button>
          <el-button
            type="success"
            class="!rounded-button"
            @click="handleImport"
          >
            <el-icon class="mr-1">
              <Upload /> </el-icon
            >导入
          </el-button>
          <el-button
            type="warning"
            class="!rounded-button"
            @click="handleExport"
          >
            <el-icon class="mr-1">
              <Download /> </el-icon
            >导出
          </el-button>
        </div>
      </div>
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="学生编号" prop="id" width="80" />
        <el-table-column label="学生姓名" prop="name" width="120" />
        <el-table-column label="学校名" prop="schoolName" width="120" />
        <el-table-column label="学号" prop="studentNumber" width="120" />
        <el-table-column label="学院" prop="college" width="120" />
        <el-table-column label="专业" prop="major" width="120" />
        <el-table-column label="年级" prop="grade" width="80" />
        <el-table-column label="积分" prop="points" width="80" />
        <el-table-column label="年龄" prop="age" width="80" />
        <el-table-column label="政治面貌" prop="politicalStatus" width="120" />
        <el-table-column label="特殊情况" prop="specialCase" width="120" />
        <el-table-column label="严重情况" prop="seriousCase" width="120" />
        <el-table-column label="当前状态" prop="status" width="120" />
        <el-table-column label="封禁" prop="close" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.close" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="120" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="openDialog('edit', scope.row)"
              >修改</el-button
            >
            <el-button type="primary" link @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleResetPassword(scope.row)"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
        width="500px"
        destroy-on-close
      >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="学生编号" prop="id">
            <el-input v-model="form.id" placeholder="请输入学生编号" />
          </el-form-item>
          <el-form-item label="学生姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入学生姓名" />
          </el-form-item>
          <el-form-item label="学校名" prop="schoolName">
            <el-select v-model="form.schoolName" placeholder="请选择学校名">
              <el-option
                v-for="school in schoolOptions"
                :key="school.id"
                :label="school.name"
                :value="school.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学号" prop="studentNumber">
            <el-input v-model="form.studentNumber" placeholder="请输入学号" />
          </el-form-item>
          <el-form-item label="学院" prop="college">
            <el-select v-model="form.college" placeholder="请选择学院">
              <el-option
                v-for="college in collegeOptions"
                :key="college.id"
                :label="college.name"
                :value="college.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="major">
            <el-select v-model="form.major" placeholder="请选择专业">
              <el-option
                v-for="major in majorOptions"
                :key="major.id"
                :label="major.name"
                :value="major.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="年级" prop="grade">
            <el-select v-model="form.grade" placeholder="请选择年级">
              <el-option
                v-for="grade in gradeOptions"
                :key="grade.id"
                :label="grade.name"
                :value="grade.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="积分" prop="points">
            <el-input v-model="form.points" placeholder="请输入积分" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄" />
          </el-form-item>
          <el-form-item label="政治面貌" prop="politicalStatus">
            <el-input
              v-model="form.politicalStatus"
              placeholder="请输入政治面貌"
            />
          </el-form-item>
          <el-form-item label="特殊情况" prop="specialCase">
            <el-input v-model="form.specialCase" placeholder="请输入特殊情况" />
          </el-form-item>
          <el-form-item label="严重情况" prop="seriousCase">
            <el-input v-model="form.seriousCase" placeholder="请输入严重情况" />
          </el-form-item>
          <el-form-item label="当前状态" prop="status">
            <el-input v-model="form.status" placeholder="请输入当前状态" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit(formRef)"
              >确认</el-button
            >
          </span>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>
  </div>

  <!-- 上传文件弹窗 -->
  <el-upload
    ref="upload"
    :action="uploadUrl"
    :before-upload="beforeUpload"
    :on-success="handleUploadSuccess"
    :on-error="handleUploadError"
    accept=".xls,.xlsx"
    show-file-list="false"
    :auto-upload="false"
  >
  </el-upload>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import * as XLSX from "xlsx"; // 引入 xlsx 库
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";


// 选中的行的ID数组
const selectedRowKeys = ref([]);

const handleSelectionChange = (selection) => {
    selectedRowKeys.value = selection.map(item => item.id);
};

// 重置搜索表单
const handleReset = () => {
  searchForm.value = {
    keyword: "",
    username: "",
    phone: "",
    status: "",
  };
  // 这里可以根据需要重新加载表格数据
};
//搜索栏数据
const searchForm = ref({
  keyword: "",
  username: "",
  phone: "",
  status: "",
  dateRange: [],
});

//表格内容
const tableData = ref([
  {
    id: 1,
    name: "张三",
    schoolName: "某某学校",
    college: "工程学院",
    major: "计算机科学",
    studentNumber: "210077",
    grade: "大二",
    points: 98,
    age: 20,
    politicalStatus: "共青团员",
    specialCase: "无",
    seriousCase: "无",
    status: "升学",
    close: true,
    createTime: "2021-09-01",
  },
]);

//分页
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 100,
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref("");
const formRef = ref<FormInstance>();
const form = ref({
  id: "",
  name: "",
  schoolName: "",
  college: "",
  major: "",
  grade: "",
  points: 0,
  age: 0,
  politicalStatus: "",
  specialCase: "",
  seriousCase: "",
  status: true,
  createTime: "",
  studentNumber: 0,
});
const rules = {
  id: [{ required: true, message: "请输入学生编号", trigger: "blur" }],
  name: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
  schoolName: [{ required: true, message: "请选择学校名", trigger: "change" }],
  college: [{ required: true, message: "请选择学院", trigger: "change" }],
  major: [{ required: true, message: "请选择专业", trigger: "change" }],
  grade: [{ required: true, message: "请选择年级", trigger: "change" }],
  points: [{ required: true, message: "请输入积分", trigger: "blur" }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  politicalStatus: [
    { required: true, message: "请输入政治面貌", trigger: "blur" },
  ],
  specialCase: [{ required: true, message: "请输入特殊情况", trigger: "blur" }],
  seriousCase: [{ required: true, message: "请输入严重情况", trigger: "blur" }],
};

const schoolOptions = reactive([
  { id: 1, name: "某某学校" },
  // 其他学校选项...
]);

const collegeOptions = reactive([
  { id: 1, name: "工程学院" },
  // 其他学院选项...
]);

const majorOptions = reactive([
  { id: 1, name: "计算机科学" },
  // 其他专业选项...
]);

const gradeOptions = reactive([
  { id: 1, name: "大一" },
  // 其他专业选项...
]);

const openDialog = (type: string, row?: any) => {
  dialogType.value = type;
  if (type === "edit" && row) {
    // 当前行为编辑模式，填充表单数据
    form.value = {
      name: row.name,
      schoolName: row.schoolName,
      college: row.college,
      major: row.major,
      grade: row.grade,
      points: row.points,
      age: row.age,
      politicalStatus: row.politicalStatus,
      specialCase: row.specialCase,
      seriousCase: row.seriousCase,
      status: row.status,
      createTime: row.createTime,
      studentNumber: row.studentNumber,
      id: row.id, // 保存当前行的ID以便后续处理
    };
  } else {
    // 清空表单数据
    form.value = {
      id: "",
      name: "",
      schoolName: "",
      college: "",
      major: "",
      grade: "",
      points: 0,
      age: 0,
      politicalStatus: "",
      specialCase: "",
      seriousCase: "",
      status: true,
      createTime: "",
      studentNumber: 0,
    };
  }
  dialogVisible.value = true;
};

//提交
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      console.log("提交表单", form);
      dialogVisible.value = false;
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "修改成功");
    }
  });
};

//删除用户
const handleDelete = (row: any) => {
  // 获取当前选中的行
  const selectedRows = tableData.value.filter(row => selectedRowKeys.value.includes(row.id));
    
    if (selectedRows.length === 0) {
        ElMessage.warning('请至少选择一项进行删除');
        return;
    }

    ElMessageBox.confirm(
        '确定要删除选中的用户吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 模拟删除操作
        selectedRows.forEach(row => {
            tableData.value = tableData.value.filter(item => item.id !== row.id);
        });
        ElMessage.success('删除成功');
    }).catch(() => { });
};

//重置密码
const handleResetPassword = (row: any) => {
  ElMessageBox.confirm("确定要重置该用户的密码吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log("重置密码", row);
      ElMessage.success("密码重置成功");
    })
    .catch(() => {});
};

// 导入功能
const handleImport = () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".xlsx, .xls";
  input.onchange = (e: any) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event: any) => {
        const data = event.target.result;
        const wb = XLSX.read(data, { type: "array" });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
        console.log("导入数据:", json);
        // 假设你将数据存入 tableData
        tableData.value = json.slice(1).map((row: any) => {
          return {
            id: row[0],
            username: row[1],
            nickname: row[2],
            phone: row[3],
            account: row[4],
            address: row[5],
            status: row[6] === "启用", // 状态转换
            createTime: row[7],
          };
        });
        ElMessage.success("文件导入成功");
      };
      reader.readAsArrayBuffer(file);
    }
  };
  input.click();
};

// 导出功能
const handleExport = () => {
  const ws = XLSX.utils.json_to_sheet(tableData); // 将 tableData 转为 sheet
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
  const data = new Blob([excelBuffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });
  const url = window.URL.createObjectURL(data);
  const link = document.createElement("a");
  link.href = url;
  link.download = "用户数据.xlsx"; // 设置下载的文件名
  link.click();
  ElMessage.success("文件导出成功");
};
</script>

<style scoped></style>
